package cn.hy.spider;

import cn.hutool.core.util.StrUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;


public class SinglePictureDownloader {
    private String referer;
    private CloseableHttpClient httpClient;
    private Picture picture;
    private String filePath;


    public SinglePictureDownloader(Picture picture, String referer, String filePath) {
        this.httpClient = HttpClientUtil.getHttpClient();
        this.picture = picture;
        this.referer = referer;
        this.filePath = filePath;
    }

    public void download() {
//        HttpGet get = new HttpGet(URLUtil.encode(picture.getUrl()));
        HttpGet get = new HttpGet(picture.getUrl());
        //设置请求头
        get.setHeader("User-Agent", UserAgentUtil.randomUserAgent());
        get.setHeader("referer", referer);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)
                .setConnectionRequestTimeout(15000).setProxy(new HttpHost("127.0.0.1", 7890)).build();
        get.setConfig(requestConfig);
        HttpEntity entity = null;
        try (CloseableHttpResponse response = httpClient.execute(get)) {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                entity = response.getEntity();
                if (entity != null) {
                    File picFile = null;
                    if (StrUtil.isNotBlank(picture.getFullPath())) {
                        picFile = new File(picture.getFullPath());
                    } else {
                        picFile = new File(filePath, picture.getTitle());
                    }
                    try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(picFile.toPath()))) {
                        entity.writeTo(out);
                        System.out.println("下载完毕：" + picFile.getAbsolutePath());
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭实体，关于 httpClient 的关闭资源，有点不太了解。
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}